import { createEmptyCard, fsrs, generatorParameters, Rating } from 'ts-fsrs';

// 生成参数
const params = generatorParameters({ enable_fuzz: true });

// 创建FSRS实例
const f = fsrs(params);

// 定义难度级别判断函数
function determineDifficulty(responseTimeMs: number, errorCount: number): Rating {
  // 5秒内选择正确为Easy
  if (responseTimeMs <= 5000 && errorCount === 0) {
    return Rating.Easy;
  }
  // 20秒内选择正确为Good
  else if (responseTimeMs <= 20000 && errorCount === 0) {
    return Rating.Good;
  }
  // 一次选错为Hard
  else if (errorCount === 1) {
    return Rating.Hard;
  }
  // 两次及以上选错为Again
  else {
    return Rating.Again;
  }
}

// 计算下次复习时间的函数
export function calculateNextReviewTime(
  currentTime: Date,
  responseTimeMs: number,
  errorCount: number,
  card?: any
): { nextReviewTime: Date; card: any } {
  // 如果没有提供卡片，则创建一个新卡片
  const newCard = card || createEmptyCard(currentTime);

  // 设置卡片状态 (state) - 0 表示新卡片
  if (!card) {
    newCard.state = 0;
    // 直接设置state属性后添加调试输出，确保它被正确赋值
    console.log('newCard.state after setting:', newCard.state);
    console.log('newCard properties:', Object.keys(newCard));
    console.log('newCard detailed:', JSON.stringify(newCard, null, 2));
  } else {
    // 打印现有卡片的状态
    console.log('Existing card state:', newCard.state);
  }

  // 打印卡片对象，检查其结构
  console.log('newCard:', newCard);

  // 确定难度级别
  const difficulty = determineDifficulty(responseTimeMs, errorCount);

  // 使用FSRS算法更新卡片并计算下次复习时间
  try {
    // 将difficulty字符串映射到ts-fsrs的rating系统
    const rating = difficulty === 'Easy' ? 4 : difficulty === 'Good' ? 3 : difficulty === 'Hard' ? 2 : 1;
    console.log('Using rating:', rating);
    const result = f.repeat(newCard, currentTime, rating);
    console.log('fsrs.repeat result:', result);
    
    // 从result对象中获取第一个有效的复习计划
    // 根据官方示例，result对象包含键为'1'到'4'的复习计划
    let reviewItem = null;
    for (const key in result) {
      if (Object.prototype.hasOwnProperty.call(result, key)) {
        const item = result[key];
        console.log(`Review plan ${key}:`, item);
        if (item.log && item.log.due) {
          reviewItem = item;
          break;
        }
      }
    }
    
    // 返回下次复习时间和更新后的结果
    if (reviewItem) {
      return {
        nextReviewTime: reviewItem.log.due as Date,
        card: reviewItem.card
      };
    } else {
      console.error('Could not find valid review item in result');
      throw new Error('Invalid result structure from fsrs.repeat');
    }
  } catch (error) {
    console.error('Error in fsrs.repeat:', error);
    throw error;
  }
}

// 示例使用
function exampleUsage() {
  const currentTime = new Date();
  
  // 示例1: 5秒内选择正确 (Easy)
  const example1 = calculateNextReviewTime(currentTime, 3000, 0);
  console.log('示例1 (Easy): 下次复习时间:', example1.nextReviewTime);
  
  // 示例2: 15秒内选择正确 (Good)
  const example2 = calculateNextReviewTime(currentTime, 15000, 0);
  console.log('示例2 (Good): 下次复习时间:', example2.nextReviewTime);
  
  // 示例3: 一次选错 (Hard)
  const example3 = calculateNextReviewTime(currentTime, 10000, 1);
  console.log('示例3 (Hard): 下次复习时间:', example3.nextReviewTime);
  
  // 示例4: 两次选错 (Again)
  const example4 = calculateNextReviewTime(currentTime, 8000, 2);
  console.log('示例4 (Again): 下次复习时间:', example4.nextReviewTime);
}

exampleUsage();